const util = require('../../../../../../utils/util.js');
const api = require('../../../../../../config/api.js');
const user = require('../../../../../../services/user.js');
const common = require('../../../../../../utils/common.js');
const app = getApp();
Page({
  data: {
    iCode: '',
  },
  onShow: function () {
    var _this = this;
    wx.login({
      success: function (res) {
        _this.setData({
          iCode: res.code
        })
      }
    });
  },
  //授权手机号的弹窗
  getPhoneNumber: function (e) {
    var _this = this;
    if (e.detail.errMsg == 'getPhoneNumber:fail user deny') {
      wx.showToast({
        title: '获取手机号失败',
        icon: 'none',
        duration: 2000
      })
    } else {
      // 同意授权
      var encryptedData = e.detail.encryptedData;
      var iv = e.detail.iv;
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var data = {};
        data.encryptedData = encryptedData;
        data.iv = iv;
        data.openid = app.globalData.logininfo.openid;
        data.code = _this.data.iCode;
        data.access_token = res.access_token;
        data.sessionkey = app.globalData.logininfo.sessionkey;
        util.post(api.Home_UpdateUserMobileApiUrl, data).then(function (res) {
          if (res.code == 200) {
            var logininfo = app.globalData.logininfo;
            logininfo.userInfo.mobile = res.result.str;
            wx.setStorage({
              key: 'logininfo',
              data: logininfo
            })
            wx.navigateBack({
              delta: 1
            })
          }
        })
      })
    }
  },
})